//
//  ProfileViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/2/7.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import AlamofireImage
import Async

class ProfileViewController: TableViewController {
    
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var sexLabel: UILabel!
    @IBOutlet weak var mobileLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
    
    var imagePicker:LSFImagePickerController?
    
    
    private var inputProfilePhoto: String?
    private var inputName: String?
    private var inputGender: Gender?
    private var inputEmail: String?
    
    static func controller() -> ProfileViewController {
        let vc = ProfileViewController.viewController(storyboardName: "Mine") as! ProfileViewController
        return vc
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.tableFooterView = UIView()
        updateUI()
   
        //获取用户信息
        startAnimating()
        shurenProvider.rx.request(.userInfo)
            .asObservable()
            .mapRespnseToObject(type:AccountModel.self)
            .subscribe(onNext: { (account) in
                AccountStorage.default.updateAccount(account)

            }, onError: { (error) in
                showError(error)
                stopAnimating()
            }, onCompleted: { [weak self] in
                self?.updateUI()
                stopAnimating()
            }).disposed(by: disposeBag)
    }
    
    func updateUI() {
        let account = AccountStorage.default.account
        
        
        if let imageUrl = account.profilePhoto  {
            if let url = URL.init(string: imageUrl) {
                avatarImageView.af_setImage(withURL: url, placeholderImage: UIImage.init(named: "default_avatar"))
            }
        }
        
        nameLabel.text = account.fullName
        mobileLabel.text = account.mobile
        sexLabel.text = account.gender?.descrip()
        emailLabel.text = account.email
    }
    
    
    @IBAction func backClick(_ sender: UIBarButtonItem) {
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func saveClick(_ sender: UIBarButtonItem) {
        var para = [String: Any]()
        if inputName != nil {
            para["fullName"] = inputName!
        }
        if inputProfilePhoto != nil {
            para["profilePhoto"] = inputProfilePhoto!
        }
        if inputGender != nil {
            para["gender"] = inputGender!.rawValue
        }
        if inputEmail != nil {
            para["email"] = inputEmail!
        }
        
        if para.count > 0 {
            startAnimating()
            AccountService.updateUserInof(para: para, success: { [weak self] (_, _) in
                stopAnimating()
                Async.main({ [weak self] in
                    self?.updateAccount()
                    self?.navigationController?.popViewController(animated: true)
                })
            }, failure: { (code, msg) in
                stopAnimating()
                lsf_alert(msg)
            })
        }
    }
    
    private func updateAccount() {
        let account = AccountStorage.default.account
        if inputName != nil {
            account.fullName = inputName
        }
        if inputProfilePhoto != nil {
            account.profilePhoto = inputProfilePhoto
        }
        if inputGender != nil {
            account.gender = inputGender
        }
        if inputEmail != nil {
            account.email = inputEmail
        }
        
        AccountStorage.default.updateAccount()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        if indexPath.row == 3 {
            return false
        }
        return true
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        switch indexPath.row {
            
            ///头像
        case 0:
            setImage()
          
           //姓名
        case 1:
            lsf_showTextFieldAlert(title: "输入您的姓名", placeholder: "姓名", presentController:self, complete: { [weak self] (str) in
                self?.nameLabel.text = str
                self?.inputName = str
            })
            
            //性别
        case 2:
            lsf_alert(style: .actionSheet, viewController: self, actionTitles: ["男", "女"], cancelTitle: "取消", sourceView: self.view, handle: { [weak self] (title) in
                if title == "男" {
                    self?.sexLabel.text = "男"
                    self?.inputGender = .male
                }
                else if title == "女" {
                    self?.sexLabel.text = "女"
                    self?.inputGender = .female
                }
            })
            
            //邮箱
        case 4:
            lsf_showTextFieldAlert(title: "输入您的邮箱", placeholder: "邮箱", presentController:self, complete: { [weak self] (str) in
                self?.emailLabel.text = str
                self?.inputEmail = str
            })
        default:
            break
        }
    }
    
    //上传头像
    private func setImage() {
        imagePicker = LSFImagePickerController()
        imagePicker?.showActionsheet(controller: self, completion: { [weak self] (imagePicker, info, image, imageData) in
            
            if image != nil {
                self?.avatarImageView.image = image
                let uploadImage = UploadImageTool.init(image: image!, resultHandle: { [weak self] (url) in
                    self?.inputProfilePhoto = url
                    stopAnimating()
                })
                startAnimating()
                uploadImage.upload()
            }
            }, quality: 0.5)
    }
    
    

}
